package com.zhijian.warehouse.manage.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.zhijian.util.BeanUtil;
import com.zhijian.util.page.Page;
import com.zhijian.warehouse.manage.dao.AccessFacilityRecordMapper;
import com.zhijian.warehouse.manage.entity.export.AccessFacilityRecordExportVo;
import com.zhijian.warehouse.manage.entity.export.AccessIllegalRecordExport;
import com.zhijian.warehouse.manage.entity.po.AccessFacilityRecord;
import com.zhijian.warehouse.manage.entity.vo.request.*;
import com.zhijian.warehouse.manage.entity.vo.response.AccessFacilityRecordVo;
import com.zhijian.warehouse.manage.entity.vo.response.AccessProductRecordVo;
import com.zhijian.warehouse.manage.entity.vo.response.ProductVo;
import com.zhijian.warehouse.manage.enums.DelFlagEnum;
import com.zhijian.warehouse.manage.enums.DoorEnum;
import com.zhijian.warehouse.manage.enums.ProductEnum;
import com.zhijian.warehouse.manage.service.AccessFacilityRecordService;
import com.zhijian.warehouse.manage.service.AccessProductRecordService;
import com.zhijian.warehouse.manage.service.ProductService;
import com.zhijian.warehouse.manage.service.TokenService;
import com.zhijian.warehouse.manage.util.AssertCommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 通道门标签感应记录业务处理层
 *
 * @author auto
 * @version: 1.0
 * @date 2024-10-28 17:42:23
 */
@Slf4j
@Service
public class AccessFacilityRecordServiceImpl implements AccessFacilityRecordService {

    @Autowired
    private AccessFacilityRecordMapper mapper;

    @Autowired
    private ProductService productService;

    @Autowired
    private AccessProductRecordService accessProductRecordService;

    @Autowired
    private TokenService tokenService;

    @Override
    public AccessFacilityRecord selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public AccessFacilityRecordVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByIdList(List<Long> idList) {
        if (CollectionUtil.isEmpty(idList)) {
            return;
        }
        mapper.deleteByIdList(idList);
    }

    @Override
    public Long insert(AccessFacilityRecord accessFacilityRecord) {
        Date now = new Date();
        accessFacilityRecord.setCreateTime(now);
        accessFacilityRecord.setUpdateTime(now);
        return mapper.insert(accessFacilityRecord) > 0 ? accessFacilityRecord.getId() : 0L;
    }

    @Override
    public Long insertSelective(AccessFacilityRecord accessFacilityRecord) {
        Date now = new Date();
        accessFacilityRecord.setCreateTime(now);
        accessFacilityRecord.setUpdateTime(now);
        return mapper.insertSelective(accessFacilityRecord) > 0 ? accessFacilityRecord.getId() : 0L;
    }

    @Override
    public boolean update(AccessFacilityRecord accessFacilityRecord) {
        Date now = new Date();
        accessFacilityRecord.setUpdateTime(now);
        return mapper.updateByPrimaryKey(accessFacilityRecord) != 0;
    }

    @Override
    public boolean updateByPrimaryKeySelective(AccessFacilityRecord record) {
        Date now = new Date();
        record.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(record) != 0;
    }

    @Override
    @Transactional
    public boolean save(AccessFacilityRecordSaveOrUpdateVo saveOrUpdateVo) {
        AccessFacilityRecord accessFacilityRecord = new AccessFacilityRecord();
        BeanUtils.copyProperties(saveOrUpdateVo, accessFacilityRecord);
        //查询标签对应的产品
        ProductVo productVo = productService.selectOne(ProductSearchVo.builder().
                rfId(accessFacilityRecord.getRfId()).isDelete(DelFlagEnum.USING.value).build());
        if (BeanUtil.isEmpty(productVo))
            return false;
        accessFacilityRecord.setStatus(DoorEnum.DOOR_IN_OUT_TYPE.UN.value);
        int registerType = 0;  //登记状态 0 = 未登记 1 = 已登记
        int type = DoorEnum.DOOR_IN_OUT_TYPE.UN.value; //进出行为 1 = 出 2 =  进
        int isViolator = 1; //是否违规 0 = 正常 1 = 违规
        int facilityStatus = 0;//1 = 正常领出 2 = 违规领出 3 = 入库归还 4 = 违规入库 5 = 已领用未出门 6 = 已进门未归还
        String violatorMsg = null; //违规原因
        if (BeanUtil.isNotEmpty(productVo)) {
            accessFacilityRecord.setProductId(productVo.getId());
            String drawTime = null;
            String backTime = null;
            if (productVo.getUseStatus() == ProductEnum.UseStatusEnum.NO.getCode().byteValue()) {
                type = DoorEnum.DOOR_IN_OUT_TYPE.OUT.value;
                drawTime = DateUtil.formatDateTime(new Date());
            }
            else {
                type = DoorEnum.DOOR_IN_OUT_TYPE.IN.value;
                backTime = DateUtil.formatDateTime(new Date());
            }
            //查询登记记录
            AccessProductRecordVo accessProductRecordVo = accessProductRecordService.selectOne(AccessProductRecordSearchVo.builder()
                    .productId(accessFacilityRecord.getProductId())
                    .type(1)
                    .searchTime(DateUtil.formatDateTime(new Date()))
                    .build());
            if (BeanUtil.isNotEmpty(accessProductRecordVo)) {
                accessFacilityRecord.setAccessProductRecordId(accessProductRecordVo.getId());
                //查询当前登陆人是否可领用
              /*  Product product = productService.selectById(productVo.getId());
                Long drawUserId = accessProductRecordVo.getDrawUserId();
                if (BeanUtil.isNotEmpty(product) && BeanUtil.isNotEmpty(drawUserId)) {
                    boolean isUserAuthorized = BeanUtil.isNotEmpty(product.getUserIds()) && product.getUserIds().contains(String.valueOf(drawUserId));
                    boolean isGroupAuthorized = BeanUtil.isNotEmpty(product.getGroupIds()) && product.getGroupIds().contains(String.valueOf(drawUserId));
                    if (!isUserAuthorized && !isGroupAuthorized) {
                        violatorMsg = "领用人未授权";
                    }
                }*/
                facilityStatus = BeanUtil.isEmpty(accessProductRecordVo.getBackTime()) ? 1 : 3;//1 = 正常领出 3 = 入库归还
                registerType = 1;
            }
            else {
                violatorMsg = "过门时间不在领用范围内";
                facilityStatus = type == DoorEnum.DOOR_IN_OUT_TYPE.OUT.value ? 2 : 3;//2 = 违规领出; 3 = 入库归还
            }
            isViolator = BeanUtil.isEmpty(violatorMsg) ? 0 : 1;
        }
        saveOrUpdateVo.setIsViolator(isViolator);
        accessFacilityRecord.setAbnType(BeanUtil.isEmpty(violatorMsg) ? 1 : 0);
        accessFacilityRecord.setType(type);
        accessFacilityRecord.setViolatorMsg(violatorMsg);
        accessFacilityRecord.setRegisterType(registerType);
        accessFacilityRecord.setIsViolator(isViolator);
        accessFacilityRecord.setStatus(facilityStatus);
        return this.insertSelective(accessFacilityRecord) != 0;
    }

    @Override
    public boolean modify(AccessFacilityRecordSaveOrUpdateVo saveOrUpdateVo) {
        AccessFacilityRecord old = this.selectById(saveOrUpdateVo.getId());
        AssertCommonUtil.notNull(old, "此数据不存在或者已被删除");
        AccessFacilityRecord accessFacilityRecord = new AccessFacilityRecord();
        BeanUtils.copyProperties(saveOrUpdateVo, accessFacilityRecord);
        return this.update(accessFacilityRecord);
    }

    @Override
    public AccessFacilityRecordVo selectOne(AccessFacilityRecordSearchVo accessFacilityRecordSearchVo) {
        return mapper.selectOne(accessFacilityRecordSearchVo);
    }

    @Override
    public Integer count(AccessFacilityRecordSearchVo accessFacilityRecordSearchVo) {
        return mapper.count(accessFacilityRecordSearchVo);
    }

    @Override
    public List<AccessFacilityRecordVo> selectList(AccessFacilityRecordSearchVo accessFacilityRecordSearchVo) {
        return mapper.selectList(accessFacilityRecordSearchVo);
    }

    @Override
    public List<AccessIllegalRecordExport> selectIllegalExportList(AccessFacilityRecordSearchVo accessFacilityRecordSearchVo) {
        return mapper.selectExportList(accessFacilityRecordSearchVo);
    }

    @Override
    public List<AccessFacilityRecordExportVo> selectFacilityList(AccessFacilityRecordSearchVo param) {
        return mapper.selectFacilityList(param);
    }

    @Override
    public Page<AccessFacilityRecordVo> selectPage(AccessFacilityRecordSearchVo accessFacilityRecordSearchVo) {
        AssertCommonUtil.check(Objects.isNull(accessFacilityRecordSearchVo.getPageNum()) || Objects.isNull(accessFacilityRecordSearchVo.getPageSize()), "分页参数不能为空");
        //先直接查总数
        int count = count(accessFacilityRecordSearchVo);
        //分页
        Page<AccessFacilityRecordVo> page = new Page<>(true, count, accessFacilityRecordSearchVo.getPageNum(), accessFacilityRecordSearchVo.getPageSize());
        accessFacilityRecordSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<AccessFacilityRecordVo> responseVos = this.selectList(accessFacilityRecordSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public boolean insertBatch(List<AccessFacilityRecord> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean delMsg(AccessFacilityDelVo param) {
        AssertCommonUtil.check(BeanUtil.isEmpty(param.getIds()), "请选择数据");
        for (Long id : param.getIds()) {
            this.updateByPrimaryKeySelective(AccessFacilityRecord.builder().id(id).abnType(1).build());
        }
        return true;
    }
}
